<template>
    <div class="my-upload">
    <h3 class="my-upload-plus">+</h3>
    <img v-if="imgUrl" class="my-upload-img" :src="imgUrl" alt="" />
    <input
      type="file"
      class="my-upload-input"
      @change="changeFile"
    />
  </div>
</template>

<script>
/*
事件
    getFile 参数：文件 
方法
  changeImg（url）
*/
import path from "path"
import {errorAlert} from "../utils/alert"
export default {
  data() {
    return {
      imgUrl: "",
    };
  },
  methods: {
    changeImg(url){
      this.imgUrl=url
    },
    //获取文件
    changeFile(e) {
      //得到文件
      let file = e.target.files[0];

      //判断大小 1M=1024KB 1KB=1024B   file.size B
      if (file.size > 2 * 1024 * 1024) {
        errorAlert("文件大小最大2M");
        return;
      }
      // 判断文件类型 file name: "2.2.2.2.2.jpeg"
      let imgArr = [".jpg", ".jpeg", ".gif", ".png"];

      // let houzhui=file.name.slice(file.name.lastIndexOf("."))
      // console.log(houzhui);
      let extname = path.extname(file.name);
      if (!imgArr.includes(extname)) {
        errorAlert("请上传正确的图片格式");
        return;
      }

      // 根据文件生成一个图片地址，赋值给imgUrl
      this.imgUrl = URL.createObjectURL(file);
      //将文件传递给父组件
        this.$emit("getFile",file)
    },
  },
};
</script>

<style scoped lang="less">
@import "../less/index.less";
.my-upload {
  width: 100px;
  height: 100px;
  border: 1px dashed @primary;
  position: relative;
}
.my-upload-plus {
  width: 100%;
  height: 100%;
  text-align: center;
  line-height: 100px;
}
.my-upload-input {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  cursor: pointer;
  opacity: 0;
}
.my-upload-img {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
}
</style>